package com.btr.ivle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.btr.ivle.R;
import com.btr.ivle.backgroud.AsyncTaskCompleteListener;
import com.btr.ivle.backgroud.GetModulesTask;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.DatabaseModule;
import com.btr.ivle.helper.DatabaseModuleItem;
import com.btr.ivle.helper.IsNetworkAvailable;
import com.btr.ivle.helper.ModuleDetailAdapter;

public class ListModuleItemActivity2 extends SherlockActivity implements 
ActionBar.OnNavigationListener, AsyncTaskCompleteListener<String> {
    public final static String EXTRA_MESSAGE_COURSECODE = "ListModuleItemActivity.COURSECODE";
    public final static String EXTRA_MESSAGE_COURSEID = "ListModuleItemActivity.COURSEID";
    public final static String EXTRA_MESSAGE_ID = "ListModuleItemActivity.ID";
    
    private int position;
    private String CourseCode;
    private ActionBar ab;
    private MenuItem item;
    private Context context = this;
    private GetModulesTask getModuleTask;
	private static final String MODULEITEM_TYPE_WORKBIN = 		"0";
	private static final String MODULEITEM_TYPE_ANNOUCEMENT = 	"1";
	private static final String MODULEITEM_TYPE_FORUM = 		"2";
	private static final String MODULEITEM_TYPE_WEBCAST = 		"3";
	private static final String MODULEITEM_TYPE_GRADEBOOK = 	"4";
	private static final String MODULEITEM_TYPE_WEBLINK = 		"5";
    
    public void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_Sherlock_Light); //Used for theme switching in samples
        super.onCreate(savedInstanceState);
        setContentView(R.layout.moduledetail_new2);
        
    	Intent intent = getIntent();
    	position = Integer.valueOf(intent.getStringExtra(MainActivity.EXTRA_MESSAGE));
    	try{
    		position = savedInstanceState.getInt("position");
    	}catch(Exception ex){
	    }
    	setActionBar();
    	
    }
    
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	  super.onSaveInstanceState(savedInstanceState);
	  savedInstanceState.putInt("position", position);
	}

    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    	position = itemPosition;
    	DatabaseModule db = new DatabaseModule(this,IVLEToken.getUserID(),null,getResources().getInteger(R.integer.DBVersion));
        String table = IVLEToken.getUserID(); 
        String[] columns = new  String[] {db.colName, db.colCode}; 
        String orderBy = db.colCode + " ASC"; 
        Cursor c = db.getReadableDatabase().query(table, columns, 
        		null, null, null, null, orderBy, null);
        c.moveToPosition(itemPosition);
        CourseCode = c.getString(1);
        setListView(CourseCode);
    	c.close();
        db.getReadableDatabase().close();
        db.close();
        return true;
    }
    
    private void setActionBar(){
    	this.ab = getSupportActionBar();
        Context context = ab.getThemedContext();
        String CourseCode = null;
        
    	ArrayAdapter<CharSequence> codeList = new ArrayAdapter<CharSequence>(context, R.layout.sherlock_spinner_item);

        DatabaseModule dbModule = new DatabaseModule(context,IVLEToken.getUserID(),null,getResources().getInteger(R.integer.DBVersion));
        String table = IVLEToken.getUserID(); 
        String[] columns = new  String[] {dbModule.colCode, dbModule.colName}; 
        String orderBy = dbModule.colCode + " ASC"; 
        Cursor c = dbModule.getReadableDatabase().query(table, columns, 
        		null, null, null, null, orderBy, null);
        c.moveToFirst();
        for  ( int  i =  0 ; i < c.getCount(); i++) { 
    		codeList.add(c.getString(0));
    		if(i==position){
    			CourseCode = c.getString(0);
    		}
	        c.moveToNext();
        }
        c.close();
        dbModule.getReadableDatabase().close();
        dbModule.close();

        codeList.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
        ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        ab.setListNavigationCallbacks(codeList, this);
        ab.setDisplayShowHomeEnabled(false);
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setSelectedNavigationItem(position);
        
        setListView(CourseCode);
    }
    
    private void setListView(String code){
    	final String CourceCode = code;
    	GridView gv = (GridView) this.findViewById(R.id.moduledetailnewItems);
    	List<Map<String, String>> itemList = new ArrayList<Map<String, String>>();
		Map<String, String> map;
		
    	DatabaseModule dbModule = new DatabaseModule(this,IVLEToken.getUserID(),null,getResources().getInteger(R.integer.DBVersion)); 
		String table = IVLEToken.getUserID(); 
		String[] columns = new  String[] {dbModule.colWorkbins, dbModule.colForums, dbModule.colWebcasts, 
				dbModule.colGradebooks, dbModule.colWebLinks, dbModule.colID, dbModule.colNewAnnounce};
		String selection = dbModule.colCode + "=?";
		String[] selectionArgs = new  String[] {code};
		String orderBy = dbModule.colCode + " ASC"; 
		Cursor c = dbModule.getReadableDatabase().query(table, columns, 
				selection, selectionArgs, null, null, orderBy, null);
		
		c.moveToFirst();
		final int nWorkbin = c.getInt(0);
		final int nForum = c.getInt(1);
		final int nWebcast = c.getInt(2);
		final int nGradebook = c.getInt(3);
		final int nWeblink = c.getInt(4);
		final String CourseID = c.getString(5);
		final String unreadAnnouncement = c.getString(6);
		int unread;
		String unreadS;
		
		map = new HashMap<String, String>();
		map.put("item", "Announcement");
		map.put("type", MODULEITEM_TYPE_ANNOUCEMENT);
		map.put("unread", unreadAnnouncement);
		itemList.add(map);
		
		List<Map<String, String>> workbinList = null;
		List<Map<String, String>> forumList = null;
		if(nWorkbin>0){
			unread = 0;
			workbinList = getItems("Workbin", code);
			for(Map<String, String> temp:workbinList){
				unread += Integer.valueOf(temp.get("unread"));
			}
			if(unread<100)
				unreadS = String.valueOf(unread);
			else
				unreadS = "99+";
			map = new HashMap<String, String>();
			map.put("item", "Workbin");
			map.put("type", MODULEITEM_TYPE_WORKBIN);
			map.put("unread", unreadS);
			itemList.add(map);
		}
		if(nForum>0){
			unread = 0;
			forumList = getItems("Forum", code);
			for(Map<String, String> temp:forumList){
				unread+= Integer.valueOf(temp.get("unread"));
			}
			if(unread<100)
				unreadS = String.valueOf(unread);
			else
				unreadS = "99+";
			map = new HashMap<String, String>();
			map.put("item", "Forum");
			map.put("type", MODULEITEM_TYPE_FORUM);
			map.put("unread", unreadS);
			itemList.add(map);
		}
		if(nWebcast>0){
			unread = 0;
			List<Map<String, String>> webcastList = getItems("Webcast", code);
			for(Map<String, String> temp:webcastList){
				unread+= Integer.valueOf(temp.get("unread"));
			}
			if(unread<100)
				unreadS = String.valueOf(unread);
			else
				unreadS = "99+";
			map = new HashMap<String, String>();
			map.put("item", "Webcast");
			map.put("type", MODULEITEM_TYPE_WEBCAST);
			map.put("unread", unreadS);
			itemList.add(map);
		}
		
		if(nGradebook>0){
			map = new HashMap<String, String>();
			map.put("item", "Gradebook");
			map.put("type", MODULEITEM_TYPE_GRADEBOOK);
			itemList.add(map);
		}
		if(nWeblink>0){
			map = new HashMap<String, String>();
			map.put("item", "Weblink");
			map.put("type", MODULEITEM_TYPE_WEBLINK);
			itemList.add(map);
		}	
		
		c.close();
		dbModule.getReadableDatabase().close();
		dbModule.close();
		
		final List<Map<String, String>> workbinListFinal = workbinList;
		final List<Map<String, String>> forumListFinal = forumList;
		ModuleDetailAdapter adapter = new ModuleDetailAdapter(this, itemList);
        gv.setAdapter(adapter);
        gv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            	int n1 = 0, n2 = 0;
            	if(position == n1){
				  Intent intent = new Intent(ListModuleItemActivity2.this, ListAnnouncementActivity.class);
				  intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
				  startActivityForResult(intent, 1);
            	}
            	n2 += (nWorkbin>0?1:0);
            	if(position > n1 && position <= n2){
            		final Intent intent = new Intent(ListModuleItemActivity2.this, ViewWorkbinActivity.class);
        			intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
        			intent.putExtra(EXTRA_MESSAGE_COURSEID, CourseID);
            		if(nWorkbin==1){
            			intent.putExtra(EXTRA_MESSAGE_ID, workbinListFinal.get(0).get("id"));
            			startActivity(intent);
            		}else{
            			ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
            			for(Map<String, String> temp:workbinListFinal){
            				adapter.add(temp.get("name"));
            			}
                    	AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    	builder.setTitle("Seletc a workbin: ");
                    	builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                    	    public void onClick(DialogInterface dialog, int item) {
                    	    	intent.putExtra(EXTRA_MESSAGE_ID, workbinListFinal.get(item).get("id"));
                    			startActivity(intent);
                    	    	}
                    		});
                    	AlertDialog alert = builder.create();
                    	alert.show();
            		}
              	}
            	n1 = n2;
            	n2 += (nForum>0?1:0);
            	if(position > n1 && position <= n2){
            		final Intent intent = new Intent(ListModuleItemActivity2.this, ListForumPostActivity.class);
            		intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
            		if(nForum==1){
            			intent.putExtra(EXTRA_MESSAGE_ID, forumListFinal.get(0).get("id"));
            			startActivity(intent);
            		}else{
            			ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
            			for(Map<String, String> temp:forumListFinal){
            				adapter.add(temp.get("name"));
            			}
                    	AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    	builder.setTitle("Seletc a forum: ");
                    	builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                    	    public void onClick(DialogInterface dialog, int item) {
                    	    	intent.putExtra(EXTRA_MESSAGE_ID, forumListFinal.get(item).get("id"));
                    			startActivity(intent);
                    	    	}
                    		});
                    	AlertDialog alert = builder.create();
                    	alert.show();
            		}
                }
            	n1 = n2;
            	n2 += (nWebcast>0?1:0);
            	if(position > n1 && position <= n2){
	  				  Intent intent = new Intent(ListModuleItemActivity2.this, ViewWebcastActivity.class);
	  				  intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
	  				  startActivityForResult(intent,1);
            	}
            	n1 = n2;
            	n2 += nGradebook;
            	if(position > n1 && position <= n2){
	  				  Intent intent = new Intent(ListModuleItemActivity2.this, ViewGradebookActivity.class);
	  				  intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
	  				  startActivityForResult(intent,1);
            	}
            	n1 = n2;
            	n2 += nWeblink;
            	if(position > n1 && position <= n2){
	  				  Intent intent = new Intent(ListModuleItemActivity2.this, ViewWeblinkActivity.class);
	  				  intent.putExtra(EXTRA_MESSAGE_COURSECODE, CourceCode);
	  				  startActivityForResult(intent,1);
            	}
            }
          });
    }
    
    private List<Map<String, String>> getItems(String item, String code){
    	List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    	Map<String, String> map;
    	
    	DatabaseModuleItem dbModuleItem = new DatabaseModuleItem(this,IVLEToken.getUserID()+"_ModuleItem",null,getResources().getInteger(R.integer.DBVersion));
		String table = IVLEToken.getUserID()+"_ModuleItem"; 
        String[] columns = new  String[] {dbModuleItem.colName, dbModuleItem.colID, dbModuleItem.colBadgeTool}; 
        String selection = dbModuleItem.colType + "=? AND " + dbModuleItem.colCode + "=?";
		String[] selectionArgs = new  String[] {item, code};
        String orderBy = dbModuleItem.colName + " ASC";
        Cursor c = dbModuleItem.getReadableDatabase().query(table, columns, 
        		selection, selectionArgs, null, null, orderBy, null);
        c.moveToFirst();
        for  ( int  i =  0 ; i < c.getCount(); i++) { 
        	map = new HashMap<String, String>();
			map.put("item", item);
			map.put("name", c.getString(0));
			map.put("id", c.getString(1));
			map.put("unread", c.getString(2));
			list.add(map);
	        c.moveToNext();
        }
        c.close();
        dbModuleItem.getReadableDatabase().close();
        dbModuleItem.close();

    	return list;
    }
    
	public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.layout.menu_refresh, menu);
        item = menu.findItem(R.id.refresh);
        return true;
    }
	
    @Override
    public boolean onOptionsItemSelected(final MenuItem item) 
    {
    	switch (item.getItemId()) {
        case android.R.id.home:
        	super.onBackPressed();
        	break;
        case R.id.refresh:
        	this.item = item;
    			if(!IVLEToken.isOffline()){
	    	        if(IsNetworkAvailable.check(context)){
	    	        	item.setActionView(R.layout.progressbarindeterminatesmall);
	    	        	getModuleTask = new GetModulesTask(context);
	    		        getModuleTask.execute();
	    	        }else{
	    	        	Toast.makeText(context, "No Internet, You've entered OFFLINE MODE." , Toast.LENGTH_LONG).show();
	    	        	IVLEToken.setOffline(true);
	    	        }
	            }
        	break;
    	}
          return true;
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    	int newPosition = position;
    	switch(resultCode){
	    	case 1:
		    	newPosition = Integer.valueOf(intent.getStringExtra("position"));
		    	if (newPosition!=this.position){
		    		ab.setSelectedNavigationItem(newPosition);
		    	}
		    	break;
	    	case 2:
	    		String CourseCode = intent.getStringExtra("code");
	    		DatabaseModule dbModule = new DatabaseModule(context,IVLEToken.getUserID(),null,getResources().getInteger(R.integer.DBVersion));
	            String table = IVLEToken.getUserID(); 
	            String[] columns = new  String[] {dbModule.colCode}; 
	            String orderBy = dbModule.colCode + " ASC"; 
	            Cursor c = dbModule.getReadableDatabase().query(table, columns, 
	            		null, null, null, null, orderBy, null);
	            c.moveToFirst();
	            for  ( int  i =  0 ; i < c.getCount(); i++) { 
	        		if(c.getString(0).equals(CourseCode)){
	        			newPosition = i;
	        			break;
	        		}
	    	        c.moveToNext();
	            }
	            c.close();
	            dbModule.getReadableDatabase().close();
	            dbModule.close();
	            if (newPosition!=this.position){
		    		ab.setSelectedNavigationItem(newPosition);
		    	}
	            break;
	    		
    	}
    }

	public void onAsyncTaskComplete(String result) {
		setListView(CourseCode);
		if(item!=null)
			item.setActionView(null);
	}
    
    public void onDestroy(){
    	if(this.getModuleTask!=null)
    		getModuleTask.cancel(true);
    	super.onDestroy();
    }
}